#include <cstdlib>
#include <stdlib.h>
#include <mysql/mysql.h>
#include <string.h>
#include <stdio.h>

int exe_query(MYSQL *pconn,const char * sql);

int main()
{
    //初始化
    MYSQL conn;
    MYSQL * pconn = mysql_init(&conn);
    //连接到数据库
    const char * host = "localhost";
    const char * user = "root";
    const char * passwd = "Root123!";
    const char * db = "april_db";
    pconn = mysql_real_connect(&conn,host,user,passwd,db,0,NULL,0);
    if(!pconn){
        fprintf(stderr,"%s\n",mysql_error(&conn));
        return EXIT_FAILURE;
    }
    printf("mysql connect success!\n");

#if 0
    const char * sql = "create table employee("
        "id int primary key auto_increment,"
        "name varchar(20),"
        "birth date,"
        "salary float)";
    exe_query(pconn,sql);
    const char * sql2 = "insert into employee(name,birth,salary) "
        "values('熊大','2010-1-1',9000),"
        "('熊二','2011-01-02',7000),"
        "('光头强','2000-01-02',8000),"
        "('吉吉','2011-01-02',7500),"
        "('松鼠','2016-01-02',8500)";
    exe_query(pconn,sql2);
#endif
    const char * sql3 = "select * from employee where id <= 3";
    exe_query(pconn,sql3);
    MYSQL_RES * result = mysql_store_result(pconn);
    if(result){
        int cols = mysql_num_fields(result);
        int rows = mysql_num_rows(result);
        printf("result: (%d, %d)\n",rows,cols);

        MYSQL_FIELD * pfields = mysql_fetch_field(result);
        for(int i = 0; i< cols; ++i){
            printf("%s\t",pfields[i].name);
        }
        printf("\n");

        MYSQL_ROW row;
        while((row = mysql_fetch_row(result)) != nullptr){
            for(int i = 0; i< cols; ++i){
                printf("%s\t",row[i]);
            }
            printf("\n");
        }

    }else{
        printf("no result\n");
    }

    mysql_close(pconn);


    return 0;
}


int exe_query(MYSQL *pconn,const char * sql){
    int ret = mysql_real_query(pconn,sql,strlen(sql));
    if(ret != 0){
        fprintf(stderr,"ERROR %d : %s\n",
                mysql_errno(pconn),mysql_error(pconn));
        return EXIT_FAILURE;
    }
    printf("QUERY OK, %ld row affected,\n",mysql_affected_rows(pconn));
    return 0;

}
